/**
 * 
 */
package com.airnewslinkosky.ticket.ui.login;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.airnewslinkosky.ticket.R;
import com.airnewslinkosky.ticket.model.FlightInfo;
import com.airnewslinkosky.ticket.model.SearchFlight;
import com.airnewslinkosky.ticket.model.UserResponseResult;
import com.airnewslinkosky.ticket.net.WebAccessor;
import com.airnewslinkosky.ticket.pay.util.BaseHelper;
import com.airnewslinkosky.ticket.sql.FavoriteInfoDB;
import com.airnewslinkosky.ticket.ui.BaseActivity;
import com.airnewslinkosky.ticket.ui.Main;
import com.airnewslinkosky.ticket.ui.financial.FinancialSearch;
import com.airnewslinkosky.ticket.ui.flight.FlyOrderInput;
import com.airnewslinkosky.ticket.ui.order.OrderList;
import com.airnewslinkosky.ticket.util.Constants;
import com.mobclick.android.MobclickAgent;

/**
 * @author CX
 *
 */
public class Login extends BaseActivity {
	private Button rememberUsernameBut,autoLoginBut,loginButton;
	private boolean isRemUser = true;
	private boolean isAutoLogin = true;
	private Button backBut;
	
	public static FlightInfo flight;//去程
	public static FlightInfo returnFlight;//回程
	public static SearchFlight searchFlight;
	public static String isOrderList;//是否从订单查询过来
	public static String isFinacialList;//是否从账务查询过来
	
	private SharedPreferences sp;
	
	private ProgressDialog progressDialog = null;
	public Handler myHandler;
	public final int NORESULT = 3;
	public final int ORTHERRESULT = 4;
	public final int SEARCH_ERROR=7;
	public final int NOMESSAGE_ERROR=8;
	public final int SUCCESS=0;
	
	public final String serviceType = "USER_LOGIN";
	private EditText userName,password;
	private String isMemName,autoLogin;
	
	//登录后返回的USERID
	private String userId;
	
	public static String loginEmail;
	private Toast toast;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		// 删除窗口背景
        getWindow().setBackgroundDrawable(null);
		activityList.add(this);

		sp = getSharedPreferences("UserInfoB2B", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
        
		rememberUsernameBut =  (Button) findViewById(R.id.rememberUsernameBut);
		autoLoginBut =  (Button) findViewById(R.id.autoLoginBut);
		rememberUsernameBut.setOnClickListener(onClickListener);
		autoLoginBut.setOnClickListener(onClickListener);
		
		loginButton =  (Button) findViewById(R.id.loginButton);
		loginButton.setOnClickListener(onClickListener);
		
		backBut = (Button) findViewById(R.id.backBut);
		backBut.setOnClickListener(onClickListener);
		
		
		userName = (EditText) findViewById(R.id.userName);
		password = (EditText) findViewById(R.id.password);
		
		initConfig();
		
		myHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case NORESULT:
					toast = Toast.makeText(Login.this, "登录失败,网络超时或者其他错误", Toast.LENGTH_LONG);
    				toast.setGravity(Gravity.CENTER, 0, 0);
    				toast.show();
					break;
				case SEARCH_ERROR:
					toast = Toast.makeText(Login.this, (String)msg.obj, Toast.LENGTH_LONG);
    				toast.setGravity(Gravity.CENTER, 0, 0);
    				toast.show();
					break;
				case ORTHERRESULT:
					toast = Toast.makeText(Login.this, "网络超时或者其他错误", Toast.LENGTH_LONG);
    				toast.setGravity(Gravity.CENTER, 0, 0);
    				toast.show();
					break;
				case NOMESSAGE_ERROR:
					toast = Toast.makeText(Login.this, "请填写完整信息", Toast.LENGTH_LONG);
    				toast.setGravity(Gravity.CENTER, 0, 0);
    				toast.show();
					break;
				case SUCCESS:
					String nameR = (String)msg.obj;
//	    			sp.edit().putString("loginNameB2B",nameR).commit();
//	    			sp.edit().putString("isLoninOKB2B","OK").commit();
//	    			sp.edit().putString("isAutoLoginB2B",autoLogin).commit();
	    			
					if(flight!=null) {
						Intent intent = new Intent();
						intent.setClass(Login.this, FlyOrderInput.class);
						FlyOrderInput.flight = flight;
						FlyOrderInput.searchFlight = searchFlight;
						FlyOrderInput.returnFlight = returnFlight;
						startActivity(intent);
					} else if(isOrderList!=null){
						System.out.println("isOrderList=="+isOrderList);
						Intent it = new Intent(Login.this, OrderList.class);
						startActivity(it);
					} else if(isFinacialList != null){
						Intent it = new Intent(Login.this, FinancialSearch.class);
						startActivity(it);
					} else {
						Intent intent = new Intent();
		    			intent.setClass(Login.this, Main.class);
		    			Bundle bundle=new  Bundle();
		    			bundle.putString("loginNameB2B", nameR);
		    			bundle.putString("isLoninOKB2B", "OK");
		    			bundle.putString("autoLoginB2B", autoLogin);
		    			intent.putExtras(bundle);
		    			setResult(RESULT_OK, intent);
		    			finish();
					}
	    			
	    			break;
				}
			}
		};
	}
	
	private OnClickListener onClickListener = new OnClickListener(){
		public void onClick(View v) {
			switch(v.getId()){
				case R.id.backBut:
					Intent intentR = new Intent();
					intentR.setClass(Login.this, Main.class);
					startActivity(intentR);
					break;
				case R.id.rememberUsernameBut:{//记住用户
				    String isLoninOKDB = FavoriteInfoDB.selectFlySetInfoValue(Login.this, Constants.SYSTEM_TYPE_isLoninOKB2B);
				    ContentValues values = new ContentValues();
					values.put("systemType", Constants.SYSTEM_TYPE_isLoninOKB2B);
					
					if(isRemUser) {
						rememberUsernameBut.setBackgroundResource(R.drawable.button_checked);
						isRemUser = false;
						isMemName = "true";
					} else {
						rememberUsernameBut.setBackgroundResource(R.drawable.button_unchecked);
						isRemUser = true;
						isMemName = "false";
					}
					
					values.put("systemName", isMemName);
					if(isLoninOKDB!=null && !isLoninOKDB.equals("")){
				    	FavoriteInfoDB.updateFlySetInfo(Login.this, values);
				    } else {
				    	FavoriteInfoDB.insertFlySetInfo(Login.this, values);
				    }
					Constants.isLoninOKB2B = isMemName;
					
					break;
				}
				case R.id.autoLoginBut:{//记住登录
					String isAutoLoginB2B = FavoriteInfoDB.selectFlySetInfoValue(Login.this, Constants.SYSTEM_TYPE_isAutoLoginB2B);
				    ContentValues values = new ContentValues();
					values.put("systemType", Constants.SYSTEM_TYPE_isAutoLoginB2B);
					if(isAutoLogin) {
						autoLoginBut.setBackgroundResource(R.drawable.button_checked);
						autoLogin = "true";
						isAutoLogin = false;
					} else {
						autoLoginBut.setBackgroundResource(R.drawable.button_unchecked);
						autoLogin = "false";
						isAutoLogin = true;
					}
					
					values.put("systemName", autoLogin);
					if(isAutoLoginB2B!=null && !isAutoLoginB2B.equals("")){
				    	FavoriteInfoDB.updateFlySetInfo(Login.this, values);
				    } else {
				    	FavoriteInfoDB.insertFlySetInfo(Login.this, values);
				    	System.out.println("insert Constants.isAutoLoginB2B  = " + autoLogin );
				    }
					Constants.isAutoLoginB2B = autoLogin;
					System.out.println("click Constants.isAutoLoginB2B  = " + Constants.isAutoLoginB2B );
					break;
				}
				case R.id.loginButton:{//登录
					String name = userName.getText().toString();
					String pwd = password.getText().toString();
					if ("".equals(name) || "".equals(pwd)){
						BaseHelper.showDialog(Login.this, "提示", "请填写完整信息",
	    						R.drawable.infoicon);
	    			} else {
	    				login(name,pwd);
	    			}
					break;
				}
				
			}
			
		}
	};
	
    //初始化配置

    private void initConfig() {
     String userGet = Constants.USERNAME;
     System.out.println("userGet="+userGet);
     String isLoninOKB2B = Constants.isLoninOKB2B;
     System.out.println("isLoninOKB2B="+isLoninOKB2B);
     if("true".equals(isLoninOKB2B)){
    	 rememberUsernameBut.setBackgroundResource(R.drawable.button_checked);
    	 userName.setText(userGet);
    	 isRemUser = false;
     } else {
    	 rememberUsernameBut.setBackgroundResource(R.drawable.button_unchecked);
		 isRemUser = true;
     }
    }
    
	
	private void login(final String name,final String pwd) {
		progressDialog = ProgressDialog.show(this, "请稍等...", "正在登录...",true);
		final Thread thread = new Thread() {
			public void run() {
		        try {
		        	loginEmail = name;
					UserResponseResult result = WebAccessor.userRegister(name,pwd,loginEmail,serviceType);
					if (progressDialog.isShowing()) {
						if (result.Result == null) {
							Message msg = new Message();
							msg.what = NORESULT;
							myHandler.sendMessage(msg);
						}else if(!"0".equals(result.Result)){
							Message msg = new Message();
							msg.what = SEARCH_ERROR;
							msg.obj = result.ErrorDescription;
							myHandler.sendMessage(msg);
						} else if("0".equals(result.Result)){
							Message msg = new Message();
							msg.what = SUCCESS;
							msg.obj = result.UserName;
							userId = result.UserID;
//							sp.edit().putString("loginNameB2B",result.UserName).commit();
//							sp.edit().putString("userIdB2B",userId).commit();
//							sp.edit().putString("userPwdB2B",pwd).commit();
//							sp.edit().putString("ASTokenB2B",result.ASToken).commit();
							setDB(result,pwd);
							myHandler.sendMessage(msg);
						} else {
							Message msg = new Message();
							msg.what = ORTHERRESULT;
							msg.obj = result.ErrorDescription;
							myHandler.sendMessage(msg);
						}
						progressDialog.dismiss();
					}
		        } catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread.start();
	}
	
	private void setDB(UserResponseResult result , String pwd) {
		//从本机数据库中取值
	    String userId = FavoriteInfoDB.selectFlySetInfoValue(Login.this, Constants.SYSTEM_TYPE_USERID);
	    ContentValues values = new ContentValues();
		values.put("systemType", Constants.SYSTEM_TYPE_USERID);
		values.put("systemName", result.UserID);
	    if(userId!=null && !userId.equals("")){
	    	FavoriteInfoDB.updateFlySetInfo(Login.this, values);
	    } else {
	    	FavoriteInfoDB.insertFlySetInfo(Login.this, values);
	    }
	    Constants.USERID = result.UserID;
	    
	    String userNameDB = FavoriteInfoDB.selectFlySetInfoValue(Login.this, Constants.SYSTEM_TYPE_USERNAME);
	    values = new ContentValues();
		values.put("systemType", Constants.SYSTEM_TYPE_USERNAME);
		values.put("systemName", result.UserName);
	    if(userNameDB!=null && !userNameDB.equals("")){
	    	FavoriteInfoDB.updateFlySetInfo(Login.this, values);
	    	Log.i("update name", "" + result.UserName);
	    } else {
	    	userNameDB = result.UserName;
	    	FavoriteInfoDB.insertFlySetInfo(Login.this, values);
	    	Log.i("insert name", "" + result.UserName);
	    }
	    Constants.USERNAME = result.UserName;
	    
	    
	    String userPwd = FavoriteInfoDB.selectFlySetInfoValue(Login.this, Constants.SYSTEM_TYPE_USERPWD);
	    values = new ContentValues();
		values.put("systemType", Constants.SYSTEM_TYPE_USERPWD);
		values.put("systemName", pwd);
	    if(userPwd!=null && !userPwd.equals("")){
	    	FavoriteInfoDB.updateFlySetInfo(Login.this, values);
	    	Log.i("update pwd", "" + pwd);
	    } else {
	    	FavoriteInfoDB.insertFlySetInfo(Login.this, values);
	    	Log.i("insert pwd", "" + pwd);
	    }
	    Constants.USERPWD = pwd;
	    
	    
	    String asToken = FavoriteInfoDB.selectFlySetInfoValue(Login.this, Constants.SYSTEM_TYPE_ASToken);
	    values = new ContentValues();
		values.put("systemType", Constants.SYSTEM_TYPE_ASToken);
		values.put("systemName", result.ASToken);
	    if(asToken!=null && !asToken.equals("")){
	    	FavoriteInfoDB.updateFlySetInfo(Login.this, values);
	    } else {
	    	FavoriteInfoDB.insertFlySetInfo(Login.this, values);
	    }
	    Constants.ASToken = result.ASToken;
	    
	    
	    Constants.USERID = FavoriteInfoDB.selectFlySetInfoValue(Login.this, Constants.SYSTEM_TYPE_USERID);
	    Constants.USERNAME = FavoriteInfoDB.selectFlySetInfoValue(Login.this, Constants.SYSTEM_TYPE_USERNAME);
	    Constants.USERPWD = FavoriteInfoDB.selectFlySetInfoValue(Login.this, Constants.SYSTEM_TYPE_USERPWD);
	    Constants.ASToken = FavoriteInfoDB.selectFlySetInfoValue(Login.this, Constants.SYSTEM_TYPE_ASToken);
	    Constants.isLoninOKB2B = FavoriteInfoDB.selectFlySetInfoValue(Login.this, Constants.SYSTEM_TYPE_isLoninOKB2B);
	    Constants.isAutoLoginB2B = FavoriteInfoDB.selectFlySetInfoValue(Login.this, Constants.SYSTEM_TYPE_isAutoLoginB2B);
	    
	    System.out.println("Login UserName" + Constants.USERNAME);
	    System.out.println("Login userId" + Constants.USERID);
	    System.out.println("Login userPwd" + Constants.USERPWD);
	    System.out.println("Login ASToken" + Constants.ASToken);
	    System.out.println("Login isLoninOKB2B" + Constants.isLoninOKB2B);
	    System.out.println("Login isAutoLoginB2B" + Constants.isAutoLoginB2B);
	}
	
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
}
